#include <iostream>
#include <iconv.h>
#include <cstring>
#include <uchardet/uchardet.h>
static size_t Convert(char *from_cha, char *to_cha, char *in, size_t inlen, char *out, size_t outlen)
{
	//转换上下文
	iconv_t cd;
	cd = iconv_open(to_cha, from_cha);
	if (cd == 0)
		return -1;
	std::memset(out, 0, outlen);
	char **pin = &in;
	char **pout = &out;
	//返回转换字节数的数量，但是转GBK时经常不正确 >=0就成功
	size_t re = iconv(cd, pin, &inlen, pout, &outlen);
	iconv_close(cd);
	return re;
}
std::string detectEncoding(const std::string& data) {
    uchardet_t ud = uchardet_new();
    if (!ud) {
        throw std::runtime_error("Failed to create uchardet object");
    }

    if (uchardet_handle_data(ud, data.data(), data.size()) != 0) {
        uchardet_delete(ud);
        throw std::runtime_error("Failed to handle data");
    }

    uchardet_data_end(ud);
    const char* detectedCharset = uchardet_get_charset(ud);
    if (detectedCharset) {
        std::string encoding(detectedCharset);
        uchardet_delete(ud);
        return encoding;
    } else {
        uchardet_delete(ud);
        throw std::runtime_error("Charset detection failed");
    }
}
int main()
{
    std::string input = "你好，世界！";  // 示例字符串
    try {
        std::string encoding = detectEncoding(input);
        std::cout << "Detected encoding: " << encoding << std::endl;
    } catch (const std::exception& e) {
        std::cerr << "Error: " << e.what() << std::endl;
    }
}